package com.whz.gateway.configure.grey;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * router 的灰度-负载均衡
 *
 * @author whz
 * @see GatewayReactiveLoadBalancerClientAutoConfiguration
 */
@Configuration
@ConditionalOnProperty(value = "spring.cloud.loadbalancer.ribbon.enabled", havingValue = "false")
public class GrayLoadBalancerConfiguration {

    @Bean
    @ConditionalOnMissingBean({ GrayReactiveLoadBalancerClientFilter.class })
    public GrayReactiveLoadBalancerClientFilter grayReactiveLoadBalancerClientFilter(
            LoadBalancerClientFactory clientFactory,
            LoadBalancerProperties properties) {
        return new GrayReactiveLoadBalancerClientFilter(clientFactory, properties);
    }

    @Configuration
    @LoadBalancerClient(name = "gateway-reactive-load-balance-client")
    public static class WebClientConfig {

        @Bean
        @LoadBalanced
        WebClient.Builder webClientBuilder() {
            return WebClient.builder();
        }
    }
}